package com.wgb.movie.controller;

import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.wgb.movie.annotation.AuthCheck;
import com.wgb.movie.common.BaseResponse;
import com.wgb.movie.common.DeleteRequest;
import com.wgb.movie.common.ErrorCode;
import com.wgb.movie.common.ResultUtils;
import com.wgb.movie.constant.UserConstant;
import com.wgb.movie.exception.BusinessException;
import com.wgb.movie.exception.ThrowUtils;
import com.wgb.movie.model.dto.theater.TheaterAddRequest;
import com.wgb.movie.model.dto.theater.TheaterEditRequest;
import com.wgb.movie.model.dto.theater.TheaterQueryRequest;
import com.wgb.movie.model.dto.theater.TheaterUpdateRequest;
import com.wgb.movie.model.entity.Theater;
import com.wgb.movie.model.entity.User;
import com.wgb.movie.model.vo.TheaterVO;
import com.wgb.movie.service.TheaterService;
import com.wgb.movie.service.UserService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;

/**
 * 影院接口
 */
@RestController
@RequestMapping("/theater")
@Slf4j
public class TheaterController {

    @Resource
    private TheaterService theaterService;

    @Resource
    private UserService userService;

    // region 增删改查

    /**
     * 创建影院
     *
     * @param theaterAddRequest
     * @param request
     * @return
     */
    @PostMapping("/add")
    public BaseResponse<Long> addTheater(@RequestBody TheaterAddRequest theaterAddRequest, HttpServletRequest request) {
        ThrowUtils.throwIf(theaterAddRequest == null, ErrorCode.PARAMS_ERROR);
        // todo 在此处将实体类和 DTO 进行转换
        Theater theater = new Theater();
        BeanUtils.copyProperties(theaterAddRequest, theater);
        // 数据校验
        theaterService.validTheater(theater, true);
        // todo 填充默认值

        // 写入数据库
        boolean result = theaterService.save(theater);
        ThrowUtils.throwIf(!result, ErrorCode.OPERATION_ERROR);
        // 返回新写入的数据 id
        long newTheaterId = theater.getId();
        return ResultUtils.success(newTheaterId);
    }

    /**
     * 删除影院
     *
     * @param deleteRequest
     * @param request
     * @return
     */
    @PostMapping("/delete")
    public BaseResponse<Boolean> deleteTheater(@RequestBody DeleteRequest deleteRequest, HttpServletRequest request) {
        if (deleteRequest == null || deleteRequest.getId() <= 0) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        User user = userService.getLoginUser(request);
        long id = deleteRequest.getId();
        // 判断是否存在
        Theater oldTheater = theaterService.getById(id);
        ThrowUtils.throwIf(oldTheater == null, ErrorCode.NOT_FOUND_ERROR);
        // 仅本人或管理员可删除
        if (!userService.isAdmin(request)) {
            throw new BusinessException(ErrorCode.NO_AUTH_ERROR);
        }
        // 操作数据库
        boolean result = theaterService.removeById(id);
        ThrowUtils.throwIf(!result, ErrorCode.OPERATION_ERROR);
        return ResultUtils.success(true);
    }

    /**
     * 更新影院（仅管理员可用）
     *
     * @param theaterUpdateRequest
     * @return
     */
    @PostMapping("/update")
    @AuthCheck(mustRole = UserConstant.ADMIN_ROLE)
    public BaseResponse<Boolean> updateTheater(@RequestBody TheaterUpdateRequest theaterUpdateRequest) {
        if (theaterUpdateRequest == null || theaterUpdateRequest.getId() <= 0) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        // todo 在此处将实体类和 DTO 进行转换
        Theater theater = new Theater();
        BeanUtils.copyProperties(theaterUpdateRequest, theater);
        // 数据校验
        theaterService.validTheater(theater, false);
        // 判断是否存在
        long id = theaterUpdateRequest.getId();
        Theater oldTheater = theaterService.getById(id);
        ThrowUtils.throwIf(oldTheater == null, ErrorCode.NOT_FOUND_ERROR);
        // 操作数据库
        boolean result = theaterService.updateById(theater);
        ThrowUtils.throwIf(!result, ErrorCode.OPERATION_ERROR);
        return ResultUtils.success(true);
    }

    /**
     * 根据 id 获取影院（封装类）
     *
     * @param id
     * @return
     */
    @GetMapping("/get/vo")
    public BaseResponse<TheaterVO> getTheaterVOById(long id, HttpServletRequest request) {
        ThrowUtils.throwIf(id <= 0, ErrorCode.PARAMS_ERROR);
        // 查询数据库
        Theater theater = theaterService.getById(id);
        ThrowUtils.throwIf(theater == null, ErrorCode.NOT_FOUND_ERROR);
        // 获取封装类
        return ResultUtils.success(theaterService.getTheaterVO(theater, request));
    }

    /**
     * 分页获取影院列表（仅管理员可用）
     *
     * @param theaterQueryRequest
     * @return
     */
    @PostMapping("/list/page")
    @AuthCheck(mustRole = UserConstant.ADMIN_ROLE)
    public BaseResponse<Page<Theater>> listTheaterByPage(@RequestBody TheaterQueryRequest theaterQueryRequest) {
        long current = theaterQueryRequest.getCurrent();
        long size = theaterQueryRequest.getPageSize();
        // 查询数据库
        Page<Theater> theaterPage = theaterService.page(new Page<>(current, size),
                theaterService.getQueryWrapper(theaterQueryRequest));
        return ResultUtils.success(theaterPage);
    }

    /**
     * 分页获取影院列表（封装类）
     *
     * @param theaterQueryRequest
     * @param request
     * @return
     */
    @PostMapping("/list/page/vo")
    public BaseResponse<Page<TheaterVO>> listTheaterVOByPage(@RequestBody TheaterQueryRequest theaterQueryRequest,
                                                             HttpServletRequest request) {
        long current = theaterQueryRequest.getCurrent();
        long size = theaterQueryRequest.getPageSize();
        // 限制爬虫
        ThrowUtils.throwIf(size > 20, ErrorCode.PARAMS_ERROR);
        // 查询数据库
        Page<Theater> theaterPage = theaterService.page(new Page<>(current, size),
                theaterService.getQueryWrapper(theaterQueryRequest));
        // 获取封装类
        return ResultUtils.success(theaterService.getTheaterVOPage(theaterPage, request));
    }


    /**
     * 编辑影院（给用户使用）
     *
     * @param theaterEditRequest
     * @param request
     * @return
     */
    @PostMapping("/edit")
    public BaseResponse<Boolean> editTheater(@RequestBody TheaterEditRequest theaterEditRequest, HttpServletRequest request) {
        if (theaterEditRequest == null || theaterEditRequest.getId() <= 0) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        // todo 在此处将实体类和 DTO 进行转换
        Theater theater = new Theater();
        BeanUtils.copyProperties(theaterEditRequest, theater);
        // 数据校验
        theaterService.validTheater(theater, false);
        User loginUser = userService.getLoginUser(request);
        // 判断是否存在
        long id = theaterEditRequest.getId();
        Theater oldTheater = theaterService.getById(id);
        ThrowUtils.throwIf(oldTheater == null, ErrorCode.NOT_FOUND_ERROR);
        // 仅本人或管理员可编辑
        if (!userService.isAdmin(loginUser)) {
            throw new BusinessException(ErrorCode.NO_AUTH_ERROR);
        }
        // 操作数据库
        boolean result = theaterService.updateById(theater);
        ThrowUtils.throwIf(!result, ErrorCode.OPERATION_ERROR);
        return ResultUtils.success(true);
    }

    // endregion
}
